package actions;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import model.ReviewerModel;
import model.StudentModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DbException;
public class StartReviewAction extends Action {
    // is there a way to make this global for the application?
    public final int REVIEW_PROCESS_THRESHOLD = 3;

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws DbException {
        
        // gets number of reviewers
        int numReviewers = ReviewerModel.getNumReviewers();
        request.setAttribute("numReviewers", numReviewers);
        
        // if there is enough reviews it starts the process
        if(numReviewers >= REVIEW_PROCESS_THRESHOLD && !ReviewerModel.reviewProcessHasBegun()){
            // gets arraylist of unreviewed applications
            ArrayList<Integer> unreviewedApplications = StudentModel.getUngradedApplications();
            // gets arralist of all reviewers
            ArrayList<Integer> reviewers = ReviewerModel.fetchAllId();
        
            // DISTRIBUTE THE REVIEWS
            int reviewCount = 0;
            // loop through applications
            for(int i = 0; i < unreviewedApplications.size(); i++){
                // keeps track of when to start at the beginning of reviewer list
                if(reviewCount == reviewers.size()){
                    reviewCount = 0;
                }
                
                // create review that points to current student and current reviewer
                ReviewerModel.insertReview(unreviewedApplications.get(i), reviewers.get(reviewCount));
                // add to reviewers number of unreviewed work
                ReviewerModel.incrementNotReviewed(reviewers.get(reviewCount),1);
                reviewCount++;
            }
        
            // begins reviewer process
            ReviewerModel.startReviewProcess();
            return mapping.findForward("success");
        }else{
            
            // if not it goes back to the Chairs Home
            request.getSession(false).setAttribute("reviewError", "<font color=\"red\">Not enough Reviewers, need at least three</font><br>");
            return mapping.findForward("fail");
        }
    }
    
}
